<?php
namespace Index\Controller;
use Think\Controller;
use Org\Util\Wechat;

header("Content-type: text/html; charset=utf-8"); 
class GjController extends Controller {
	public $wx = null; 
    public function _initialize(){  
        $this->wx = new Wechat(C('options'));
    }
    public function index(){//exit('@#');
        $openid = session('openid');//输出openid
        if(empty($openid)){
        	//跳转到登录页面
          //  $this->redirect('Gj/index');
          $this->redirect('Gj/wlg');
        }
		
        //判断是否是客服,如果是就直接跳转过去
        $kefu=M('rbac_manager')->where('openid="'.$openid.'"')->count();
        if ($kefu>0) {
            $this->redirect('Kefu/inlist');
        }
        $list=M('customer')->where('openid="'.$openid.'"')->find();
        if (empty($list)) {
            $this->redirect('Register/index');
        }
		
		if(empty($kefu) && empty($list)){
			$this->redirect('Register/index');
		}

        $list_now = M('customer')->where(array('openid'=>$openid))->find();
		//登录
		$login=$list_now['login'];
		if($login==0){
			$this->redirect('Enter/index');
		}
       /* $phone=$list_now['phone'];
        $list_old=M('old_customer')->where('phone="'.$phone.'"')->find();*/
        if ($list_now['status_customer']==2) {
            $this->assign('da',1);
        }else{
            $this->assign('da',0);
        }
        //调用微信类
        $weObj = new \Org\Util\Wechat(C('options'));
        $userinfo = $weObj->getUserInfo($openid);
        $img=$userinfo['headimgurl'];
        $nick=$userinfo['nickname'];
        session('nickname',$nick);
        $nickname=session('nickname');
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        $sign = $weObj->getJsSign($url);
        
        //我的消息的红色小点
        $m_list=M('customer')->where('openid="'.$openid.'"')->find();
        $m_status=$m_list['m_status'];

        //小区公告
        $list=M('notice')->where('type=1')->order('sendtime desc')->find();
        $cid=$list['contid'];
        $content=M('notice_content')->where('id="'.$cid.'"')->find();
        $con=$content['content'];
        //我的消息
        $msg_list=M('notice')->where('type!=1')->order('sendtime desc')->select();
        //P($msg_list);
        $array=array();
        foreach ($msg_list as $key => $value) {
            $type=$value['type'];   //通知还是客服评价
            $sendtype=$value['sendtype'];   //发送类型
            $conid=$value['contid'];        //模板id
            $apt_id=$value['for_apt'];      //发送的小区
            $uid=$value['for_people'];      //发送的人
            $sendtime=$value['sendtime'];
            //全部用户
            if ($sendtype==2) {
                $conte[]=M('notice_content')->where('id="'.$conid.'"')->find();      
				foreach($conte as $k =>$val){
					$conte[$key]['sendtime']=$sendtime;
				}          
                $array=$conte;
            }
            //群发
            if ($sendtype==0) {
                $for_apt=explode(',',$apt_id);
                //print_r($for_apt);exit('111');
                $people=M('customer')->where('openid="'.$openid.'"')->find();
                $plot=$people['plot'];
                if(in_array($plot,$for_apt)){
                    $conte[]=M('notice_content')->where('id="'.$conid.'"')->find();      
					foreach($conte as $k =>$val){
						$conte[$key]['sendtime']=$sendtime;
					}                    
                    $array=$conte;
                }
            }
            //单发
            if ($sendtype==1) {
                $for_people=explode(',',$uid);
                $people=M('customer')->where('openid="'.$openid.'"')->find();
                $id=$people['id'];
                if(in_array($id,$for_people)){
                    $conte[]=M('notice_content')->where('id="'.$conid.'"')->find();          
					foreach($conte as $k =>$val){
						$conte[$key]['sendtime']=$sendtime;
					}                
                    $array=$conte;
                }
            }
        }
        //P($array);exit('@#$');
        //映射我的消息的小红点
        $this->assign('m_status',$m_status);
        $this->assign('sendtime',$sendtime);
        $this->assign('nickname',$nickname);
        $this->assign('arr',$array);
        $this->assign('con',$con);
        $this->assign('sign',$sing);
        $this->assign('openid',$openid);
        $this->assign('img',$img);
        $this->display('idea');
    }
    
    
    
    //授权
    	
	function wlg(){ 
        $callback = 'http://sunwayuchoice.com/index.php/Gj/wlgback';
        $url = $this->wx->getOauthRedirect($callback);
        header('location:'.$url);
    }
    
    function wlgback(){ 
        $tk = $this->wx->getOauthAccessToken();
        session('openid',$tk['openid']);
        $this->redirect('Gj/index');
    }
    
    
    
    //编辑资料页面
    public function update_index(){
        $openid = session('openid');//输出openid
        $list=M('customer')->where('openid="'.$openid.'"')->find();//oYCoAxNz8Xmj0FKI7LhY6R49Cfuc
        //$list=M('customer')->where('openid="oYCoAxNz8Xmj0FKI7LhY6R49Cfuc"')->find();
		$plot=M('apt')->where("id=".$list['plot'])->find();
		$apt=M('apt')->select();
       // P($plot,false);
		$this->assign('plot',$plot);
		$this->assign('apt',$apt);
        $this->assign('list',$list);
        $this->display('perf');

    }

      //编辑资料
    public function update(){
        $openid = session('openid');//输出openid
        $name=trim(I('name'));
        $email=trim(I('email'));
        $birth=trim(I('birth'));
        $sex=I('sex');
        $apt=I('apt');
		$sc_list=M('apt')->where('id="'.$apt.'"')->find();
		$sc_id=$sc_list['sid'];
        $num=trim(I('num'));
        $customer=M('customer');
        $data=array(
                'sex'=>$sex,
                'name'=>$name,
                'email'=>$email,
                'birth'=>$birth,
                'plot'=>$apt,
                'num'=>$num,
                'sc'=>$sc_id,
            );
            

        $res_save=$customer->where('openid="'.$openid.'"')->data($data)->save();
        if ($res_save!==false ) {
           $this->ajaxReturn(array('s'=>'true','m'=>"修改成功"));
        }else{
           $this->ajaxReturn(array('s'=>'false','m'=>"修改失败"));
        }
        
    }


    //修改手机号
    public function update_phone(){
        $openid=session('openid');
        $list=M('customer')->where('openid="'.$openid.'"')->find();
        $arr=$this->check_form();
        $weObj = new \Org\Util\Wechat(C('options'));
        //获取签名
        $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        $sign = $weObj->getJsSign($url);
        $this->assign('sign',$sign);
        $this->assign('list',$list);
        $this->assign('arr',$arr);
        $this->display('phone');

    }
  
    //表单令牌短信验证防止重复提交
    public function check_form(){
        session("token",md5(rand(10000,99999)));
        $check=session("token");
        return $check;
    }
    
    
    //发送短信
    public function msg()
    {   
        $num=$this->randString();
        $phone=trim(I('phone'));

        $list=M('customer')->where('phone="'.$phone.'"')->find();
        if (empty($list)) {
            $this->ajaxReturn(array('s'=>'no','m'=>"您还没有注册"));
        }

        //表单令牌验证
        $token=I('token');
        if ($token!=session('token') || empty($token)){
         // 令牌验证错误
         //exit('令牌验证错误');
         $this->ajaxReturn(array('s'=>"check",'m'=>"令牌验证错误"));
        }else{
        //正则验证手机号
        if(preg_match("/^1[34578]{1}\d{9}$/",$phone)){        
            $c=Vendor('Alidayu.top.TopClient'); 
            $c=new \TopClient();
            $c->appkey =C('AlidayuAppKey');
            $c->secretKey =C('AlidayuAppSecret');
            $req=Vendor('Alidayu.top.request.AlibabaAliqinFcSmsNumSendRequest');
            $req=new \AlibabaAliqinFcSmsNumSendRequest();
            $req->setSmsType("normal");
            $req->setSmsFreeSignName("修改手机号绑定");
            $req->setSmsParam("{\"code\":\"$num\",\"product\":\"尚元优家Uchoice\"}");
            $req->setRecNum($phone);
            $req->setSmsTemplateCode("SMS_12200891");//修改密码的短信模板
            $resp = $c->execute($req);
            S($phone,$num,120);
            $this->ajaxReturn(array('s'=>'ok','m'=>"发送成功"));
        }else{  
            $this->ajaxReturn(array('s'=>"fail",'m'=>"令牌验证错误"));
        }  
     }
    }


    /**
     * 获取随机位数数字
     * @param  integer $len 长度
     * @return string       
     */
    protected static function randString($len = 4)
    {
        $chars = str_repeat('0123456789', $len);
        $chars = str_shuffle($chars);
        $str   = substr($chars, 0, $len);
        return $str;
    }


    //验证短信验证
    public function check(){
            //本地测试的时候需要注释掉
            $openid =session('openid');
            if (empty($openid)) {
                $this->ajaxReturn(array('c'=>"openid",'m'=>"出现错误,请点击注册链接重新进行注册"));
            }
            $num=I('num');
            $phone = I('phone');
            $verify = S($phone);
            if (empty($verify)) {
                //exit('验证码失效');
                $this->ajaxReturn(array('c'=>"shixiao",'m'=>"验证码失效"));
            }

            if ($verify != $num) {
                //echo '验证失败';
                $this->ajaxReturn(array('c'=>"error",'m'=>"验证码错误"));
            }else{
               $this->ajaxReturn(array('c'=>"yes",'m'=>"验证成功"));
            }
    }

    //修改手机号
    public function phone_up(){
        $openid=session('openid');
        $phone=trim(I('phone'));
        $data=array(
                'phone'=>$phone,
            );
        $res_save=M('customer')->where('openid="'.$openid.'"')->save($data);
        if (false!==$res_save) {
            echo "修改成功";exit('good');
        }
    }


    //我的优惠券
    public function coupon_list(){
        $openid = session('openid');//输出openid
        //P($openid);
        //调用微信类
        $list_now = M('customer')->where(array('openid'=>$openid))->find();
        //$phone=$list_now['phone'];
        //$list_old=M('old_customer')->where('phone="'.$phone.'"')->find();
        if ($list_now['status_customer']==2) {
            $this->assign('da',1);
        }else{
            $this->assign('da',0);
        }

        $weObj = new \Org\Util\Wechat(C('options'));
        $userinfo = $weObj->getUserInfo($openid);
        $img=$userinfo['headimgurl'];
        $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        //签名
        $sign = $weObj->getJsSign($url);
        //我的消息的红色小点
        $m_list=M('customer')->where('openid="'.$openid.'"')->find();
        $m_status=$m_list['m_status'];
        //所有优惠券
        $list=M('winner')->where('openid="'.$openid.'"')->select();
        //print_r($list);exit('#$');
        foreach ($list as $k => $v) {
            $q_name=$v['q_name'];
            $name=M('award')->where('name="'.$q_name.'"')->find();
            $list[$k]['endtime']=$name['endtime'];
            $list[$k]['starttime']=$name['starttime'];
            $endtime=$name['endtime'];
            $where_y=array('openid'=>$openid,'status'=>1,);
            $list_y=M('winner as a')->join('sy_award as b on a.q_name=b.name')->field('a.id,a.name,a.q_name,b.type,a.status,a.s_time,b.starttime,b.area,b.tiaojian,b.endtime')->where($where_y)->order('s_time desc')->select();    //已使用
            $where=array('openid'=>$openid,'status'=>0,);
            $where['endtime'] = array('gt',time());
            $list_w=M('winner as a')->join('sy_award as b on a.q_name=b.name')->field('a.id,a.name,a.q_name,b.type,a.status,a.s_time,b.starttime,b.area,b.tiaojian,b.endtime')->where($where)->select();//未使用
            //已过期
            $where1=array('openid'=>$openid,'status'=>0,);
            $where1['endtime'] = array('lt',time());
            $list_g=M('winner as a')->join('sy_award as b on a.q_name=b.name')->field('a.id,a.name,a.q_name,b.type,a.status,a.s_time,b.starttime,b.area,b.tiaojian,b.endtime')->where($where1)->select();
        }
        $arr=array('list_w'=>$list_w,'list_y'=>$list_y,'list_g'=>$list_g);
        //print_r($arr);exit;
        $this->assign('m_status',$m_status);
        $this->assign('list',$arr);
        $this->assign('sign',$sign);
        $this->assign('nickname',session('nickname'));
        $this->assign('img',$img);
        $this->display('coupon');
    }


    //核销优惠券首页
    public function c_index(){
        $id=I('id');
        $list=M('winner')->where('id="'.$id.'"')->find();
        $q_name=$list['q_name'];
        $list_a=M('award')->where('name="'.$q_name.'"')->find();
        $preg ="/<img src=\"(.+?)\".*?>/";//只能有src  
        preg_match_all($preg,html_entity_decode($list_a['img']),$cover);       
        $cover_arr=$cover[1][0];//去除数组中重复的值     
        //print_r($cover_arr);exit;
        $this->assign('img',$cover_arr);
        $this->assign('list',$list);
        $this->assign('list_a',$list_a);
        $this->display('show');

    }

    //核销
    public function hexiao(){
        $id=$_REQUEST['id'];
        $list=M('winner')->where('id="'.$id.'"')->find();
        $q_name=$list['q_name'];

        $list_a=M('award')->where('name="'.$q_name.'"')->find();
        $endtime=$list_a['endtime'];
        if (time()>$endtime || $list['status']==1) {
           error('此优惠券已经使用或过期',"http://sunwayuchoice.com/index.php/Gj/coupon_list");
        }

        $data=array(
            'status'=>1,
            's_time'=>time(),
            );
        $res_save=M('winner')->where('id="'.$id.'"')->data($data)->save();
        if (false!==$res_save) {
            error('您已经成功使用"'.$q_name.'"优惠券',"http://sunwayuchoice.com/index.php/Gj/coupon_list");     
        }

    }

    //修改消息状态
    public function m_status(){
        $openid=session('openid');
        $res=M('customer')->where('openid="'.$openid.'"')->data(array('m_status'=>1,))->save();
        $this->redirect('Gj/index');
    }


    //退出登录
    public function close(){
    	$openid=session('openid');
        $res=M('customer')->where('openid="'.$openid.'"')->data(array('login'=>0,))->save();
        session(null); // 清空当前的session
        //关闭微信窗口
        $this->display('close');
        
    }


    //客服评价
    public function pingjia(){
        $id=I('id');
       
        $list=M('notice_content')->where('id="'.$id.'"')->find();
       // P($list);
        if ($list['type']==2) {
            $content=M('kf_sc_log')->where('id="'.$list['talk_id'].'"')->find();
           // P($content,false);
            $ping_jia=$content['ping_jia'];
            //P($ping_jia);
            //$this->ajaxReturn(array('s'=>true,'m'=>'感谢您的支持'));
            $this->ajaxReturn(array('s'=>1,'m'=>$ping_jia));
        }else{

            $name=I('txt');
           
            //$openid=session('openid');
            $data=array(
                    'type'=>2,
                );
            $res=M('notice_content')->where('id="'.$id.'"')->save($data);
            ///echo M()->_sql();
            $data_talk=array(
                    'ping_jia'=>$name,
                );
           
            $content=M('kf_sc_log')->where('id="'.$list['talk_id'].'"')->save($data_talk);
               //echo M()->_sql();exit('@#$');
            $this->ajaxReturn(array('s'=>1,'m'=>'感谢您的支持'));
        }
    }



	
	public function kefu(){
		//session('openid','oYCoAxNz8Xmj0FKI7LhY6R49Cfuc'); 
		$openid = session('openid');
		
		if(empty($openid)){
			exit('Has not Login !');
		}
        $list_now = M('customer')->where(array('openid'=>$openid))->find();
        //$phone=$list_now['phone'];
        //$list_old=M('old_customer')->where('phone="'.$phone.'"')->find();
        if ($list_now['status_customer']==2) {
            $this->assign('da',1);
        }else{
            $this->assign('da',0);
        }
        $weObj = new \Org\Util\Wechat(C('options'));
        $userinfo = $weObj->getUserInfo($openid);
        $img=$userinfo['headimgurl'];
        $nick=$userinfo['nickname'];
        session('nickname',$nick);
        $nickname=session('nickname');
        //我的消息的红色小点
        $m_list=M('customer')->where('openid="'.$openid.'"')->find();
        $m_status=$m_list['m_status'];

		$user = M('Customer')->where(array('openid'=>$openid))->find(); 
		if(empty($user)){
			exit('User empty !');
		}
		
		$scid = $user['sc'];
		$this->assign('scid',$scid);
		
		$xq = M('Apt')->where(array('id'=>$user['plot']))->find();
		//P($xq);
		$this->assign('xq',$xq); 
		
		$xqList = M('Apt')->select();
		
		
		$this->assign('xqList',$xqList);
        $this->assign('img',$img);
        $this->assign('nickname',$nickname);
		$this->assign('m_status',$m_status); 
		$this->display();
	}
	
	public function getapt(){
		$id=I('scid');
		$xq = M('Apt')->where('id="'.$id.'"')->find();
		$xq_name=$xq['name'];
		$this->ajaxReturn(array('s'=>true,'d'=>$xq_name));
	}
	
	
	
	public function test(){
		$weObj = new Wechat(C('options')); 
		$conn = $weObj->getCustomServiceKFlist();
		//$conn = $weObj->deleteKFAccount('kf0006@zjit');
		P($conn); 
	}
	
	public function mlg(){
		session('openid','oYCoAxNz8Xmj0FKI7LhY6R49Cfuc');
		exit('ok');
	}
	
	public function createConnect(){
		$key = I('post.key');
		$key ='客户咨询';
		$kf_account = I('post.kf');
		$openid = session('openid'); 
		if(empty($key)||empty($kf_account)||empty($openid)){
			$this->ajaxReturn(array('s'=>false,'m'=>'Error'));
		}
		
		//判断现在用户是否在连接客服的状态下
	/*	$kf_service=$weObj->getCustomServiceKFlist();
		P($kf_service);
		*/
		
		
		$data = array(
			'openid'		=>	$openid,
			'key'			=>	$key,
			'kf_account'	=>	$kf_account,
            'created'       =>  time(),
		);
		$Md = M('Kf_tmp_key');
		$hasData = $Md->where(array('openid'=>$openid,'kf_account'	=>	$kf_account))->count(); 
		//存在即更新 
		if($hasData){
			$rs = $Md->where(array('openid'=>$openid,'kf_account'	=>	$kf_account))->save($data);
		}else{
			$rs = $Md->data($data)->add();
		}
		//保存服务日志表
		$MscLog = M('Kf_sc_log');
       
       
		$rs = $MscLog->data($data)->add();

        //session('talk_id',$rs);

		$kf = M('Kf')->where(array('kf_account'=>$kf_account))->find();
		if(empty($kf)){
			$this->ajaxReturn(array('s'=>false,'m'=>'客服不存在'));
		}
		//对接客服 
		$weObj = new Wechat(C('options')); 
		$conn = $weObj->createKFSession($openid,$kf_account,$key);
		
		if(!$conn){
			$this->ajaxReturn(array('s'=>false,'m'=>'客服连接失败,原因您已经连接其他客服,请您继续和公众号聊天'));
		}

		//获取用户小区信息
        $udata = M('customer')->where('openid="'.$openid.'"')->find();
		$xqid = $udata['plot'];
		$xq = M('Apt')->where(array('id'=>$xqid))->find();
		$xqTitle = empty($xq['name'])?'尚云':$xq['name'];
		
		$data =  array(
			"touser" =>	$kf['openid'],
			"template_id" =>	"Yu4ci-e8xVZ90dVZ1WwcUm0gJSCyy_rE0XXZ4Mc8feY",
			"url" =>	"http://sunwayuchoice.com/index.php/Kefu/talk/openid/".$openid,
			"topcolor" =>	"#FF0000",
			"data" => array( 
					'first'	=>	array(
						"value" =>	"您有新的咨询信息通知",
						"color" =>	"#ff0000"
					),
					'keyword1'	=>	array(
						"value" =>	$xqTitle,
						"color" =>	"#173177"
					),
					'keyword2'	=>	array(
						"value" =>	$key,
						"color" =>	"#173177"
					),
					'keyword3'	=>	array(
						"value" =>	"您好，".$xqTitle."的".$udata['name']."要咨询您一些有关于".$key."问题，看到后请及时登陆客服系统进行回复",
						"color" =>	"#173177"
					),
					'remark'	=>	array(
						"value" =>	"尚云云客服平台",
						"color" =>	"#173177"
					)
				)
		);
		$st = $weObj->sendTemplateMessage($data);
		if($conn['errcode']==0){
			$this->ajaxReturn(array('s'=>true,'m'=>'Success'));
		}else{
			$this->ajaxReturn(array('s'=>false,'m'=>'Error'));
		}
		
		if($conn['errcode']==0){
			$this->ajaxReturn(array('s'=>true,'m'=>'ConnecctSuccess'));
		}
	}
	
	function getkeyandmanage(){
		$scid = I('get.scid');
		$keys = M('Sc')->where('id='.$scid)->find();
		if(!empty($keys)){
			$keys = '0'.$keys['keys'].'0';
			$keyarr = M('Sckey')->where('id in ('.$keys.') ')->select();  
		} 
		$kf = M('RbacManager')->where(array('sc'=>$scid))->select();
		
			
		$weObj = new \Org\Util\Wechat(C('options'));
		//获取客服在线列表
		$kf_online=$weObj->getCustomServiceOnlineKFlist();
		$tarkf = array();
		foreach ($kf_online['kf_online_list'] as  $value) {
			$tarkf[] = $value['kf_account'];
		} 
		
		$kflist = array();
		foreach($kf as $k){
			$tk = $k;
			$tk['kf_info'] = M('Kf')->where(array('openid'=>$k['openid']))->find();
			$tk['kf_info']['online_status']= in_array($tk['kf_info']['kf_account'],$tarkf); 
			$kflist[] = $tk;
		} 
		
		$this->ajaxReturn(array('s'=>true,'m'=>'Success','d'=>array('keys'=>$keyarr,'kflist'=>$kflist,'d'=>$keys)));
	}
	
	public function tlg(){
		session('openid','oYCoAxCG9hngSCk1cXoUvd3mDFw0');
		$this->redirect('kefu');
	}
	
	function lg(){
		$weObj = new Wechat(C('options')); 
		$callback = 'http://sunwayuchoice.com/index.php/Gj/lgback';
		$url = $weObj->getOauthRedirect($callback);
		header('location:'.$url);
	}
	
	function lgback(){
		$weObj = new Wechat(C('options')); 
		$tk = $weObj->getOauthAccessToken();
		session('openid',$tk['openid']);
		$this->redirect('kefu');
	}
	
	function sMes(){
		$openid = session('openid'); 
		$data =  array(
			"touser" =>	$openid,
			"template_id" =>	"bDQM_gguAvCBTiGgRj8bPw6ZXOTonWPfeb-H9dBBmI4",
			"url" =>	"http://sunwayuchoice.com/index.php/Kefu/talk/openid/".$openid,
			"topcolor" =>	"#FF0000",
			"data" => array( 
					'first'	=>	array(
						"value" =>	"您有新的咨询信息通知",
						"color" =>	"#ff0000"
					),
					'keyword1'	=>	array(
						"value" =>	"有人咨询您",
						"color" =>	"#173177"
					),
					'keyword2'	=>	array(
						"value" =>	"2015年5月10日 19时24分",
						"color" =>	"#173177"
					),
					'keyword3'	=>	array(
						"value" =>	"您好，某小区的某某人要咨询您一些问题，看到后请及时登陆客服系统进行回复",
						"color" =>	"#173177"
					),
					'remark'	=>	array(
						"value" =>	"尚云云客服平台",
						"color" =>	"#173177"
					)
				)
			);
		$weObj = new Wechat(C('options')); 
		$st = $weObj->sendTemplateMessage($data);
		P($st);
	}
	
	//领券的授权
	 	
	function coupon_wlg(){ 
        $callback = 'http://sunwayuchoice.com/index.php/Gj/coupon_wlgback';
        $url = $this->wx->getOauthRedirect($callback);
        header('location:'.$url);
    }
    
    function coupon_wlgback(){ 
        $tk = $this->wx->getOauthAccessToken();
      //  P($tk);
        session('openid',$tk['openid']);
        $id = session('tmp_id');
        session('tmp_id',null);
        $this->redirect('Gj/sendCoupon/id/'.$id);
    }
	
	//点击链接发优惠券
	public function sendCoupon(){ 
		$id=I('id'); 
		$openid=session('openid');
		if($openid==""){
			session('tmp_id',$id);
			$this->redirect('coupon_wlg');
		}
		$list=M("award")->where(array('id'=>$id))->find();
		//P($list);
		if(empty($list)){
			error("微信网络错误","http://sunwayuchoice.com/index.php/Gj/index");
		}
		//首先先判断用户是第一次点击进来还是第二次点击进来
		$win=M('winner')->where("openid='".$openid."'")->select();
		if(!empty($win)){
			foreach ($win as $key => $value) {
			$q_name=$value['q_name'];
			$quan[]=$q_name;
			}
			//P($quan,false);
			if(in_array($list['name'],$quan)){
				error("亲，一种券只能领取一次哦，感谢您的参与，谢谢","http://sunwayuchoice.com/index.php/Gj/index");
			}
		}
		
		//判断优惠券数量
		if($list['num']<=$list['balance']){
			error("券的数量不足，感谢您的参与","http://sunwayuchoice.com/index.php/Gj/index");
		}
		
		//判断用户是否为优质用户
		$cus_type=$list['cus_type'];
		$list_cus=M("customer")->Where("openid='".$openid."'")->find();
	
		if($cus_type==1){
			
			P($list_cus,false);
			$type=$list_cus['status_customer'];
			if($type!=2){
			error("此优惠券只有vip用户可以领取，感谢您的参与","http://sunwayuchoice.com/index.php/Gj/index");	
			}
		}	
		
		//生成优惠券劵码
		$codes=A('Index/Research');
		$code=$codes->random();
		
		$data=array(
				'name'=>$list_cus['name'],
				'ctime'=>time(),
				'q_name'=>$list['name'],
				'openid'=>$openid,
				'q_ma'=>$code,
				'status'=>0,
				);
	
		$res=M("winner")->data($data)->add();
		if($res!==false){  
			  $weObj = new Wechat(C('options'));  
				$datas =  array(
					"touser" =>	$openid,
					"template_id" =>	"Yu4ci-e8xVZ90dVZ1WwcUm0gJSCyy_rE0XXZ4Mc8feY",
					"url" =>	"http://sunwayuchoice.com/index.php/Gj/coupon_list",
					"topcolor" =>	"#FF0000",
					"data" => array( 
							'first'	=>	array(
								"value" =>	"您有一张新的优惠券",
								"color" =>	"#ff0000"
							),
							'keyword1'	=>	array(
								"value" =>	'优惠券名称："'.$list['name'].'"',
								"color" =>	"#173177"
							),
							'keyword2'	=>	array(
								"value" =>	'优惠券到账通知',
								"color" =>	"#173177"
							),
							'keyword3'	=>	array(
								"value" =>	"您好，请您到个人中心查看优惠券",
								"color" =>	"#173177"
							),
							'remark'	=>	array(
								"value" =>	"尚元优家Uchoice",
								"color" =>	"#173177"
							)
						)
				);
				$st = $weObj->sendTemplateMessage($datas);
			$arr=array('balance'=>$list['balance']+1);
			$res_save=M('award')->where('id="'.$id.'"')->save($arr);
			if($res_save){
				error("恭喜您获得一张优惠券,请到个人中心进行查看","http://sunwayuchoice.com/index.php/Gj/index");
			}         
			
		}else{
			error("领取失败，感谢您的参与","http://sunwayuchoice.com/index.php/Gj/index");	
		}
	
	  
	}
	
	
	//留言
	public function liuyan(){
		$openid=session('openid');
		//查找人和小区
		$people=M('customer')->where('openid="'.$openid.'"')->find();
		$people_name=$people['name'];
		$people_phone=$people['phone'];
		$plot_find=M('apt')->where('id="'.$people['plot'].'"')->find();
		$plot_name=$plot_find['name'];
		
		$opercode="2003";
		$text=I('content');
		$time=time();
		$kf=I('kf');
		
		$kf_info=M('kf')->where('kf_account="'.$kf.'"')->find();
		$kf_openid=$kf_info['openid'];
		
		$data=array(
				'openid'  =>$openid,
				'opercode'=>$opercode,
				'text'    =>$text,
				'time'    =>$time,
				'worker'  =>$kf,
				'status'  =>1,
			);
		$res=M('msglog')->add($data);
		
		if($res!==false){
				$data = array(
					'openid'		=>	$openid,
					'key'			=>	"留言",
					'kf_account'	=>	$kf,
		            'created'       =>  time(),
		            'status'       => 1,
		            'sta'       => 1,
				);
				$res=M('kf_sc_log')->add($data);
				$weObj = new Wechat(C('options'));  
				$datas =  array(
					"touser" =>	$kf_openid,
					"template_id" =>	"Yu4ci-e8xVZ90dVZ1WwcUm0gJSCyy_rE0XXZ4Mc8feY",
					"url" =>	"http://sunwayuchoice.com/index.php/Kefu/talk/openid/".$openid,
					"topcolor" =>	"#FF0000",
					"data" => array( 
							'first'	=>	array(
								"value" =>	"您有一条新的留言",
								"color" =>	"#ff0000"
							),
							'keyword1'	=>	array(
								"value" =>	$plot_name."的".$people_name."给您留了一条留言",
								"color" =>	"#173177"
							),
							'keyword2'	=>	array(
								"value" =>	'留言通知',
								"color" =>	"#173177"
							),
							'keyword3'	=>	array(
								"value" =>	$text,
								"color" =>	"#173177"
							),
							'remark'	=>	array(
								"value" =>	"客户联系方式为".$people_phone,
								"color" =>	"#173177"
							)
						)
				);
				$st = $weObj->sendTemplateMessage($datas);
			
			$dataad=array(
				'openid'  =>$openid,
				'key'=>"留言",
				'text'    =>$text,
				'created'    =>$time,
				'kf_account'  =>$kf,
				'status'  =>1,
			);
			
			
			
			$this->ajaxReturn(array('s'=>"ok",'m'=>"留言成功，感谢您对我们工作的支持"));
		}else{
			$this->ajaxReturn(array('s'=>"no",'m'=>"留言失败，请您等待或寻找其他客服，谢谢"));
		}
	}
}
?>